package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    检查登录
*/
@WebFilter(value = {"/addStudent.jsp","/listStudentServlet"})
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //try {
            // 转换为HTTP协议
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;

            // 获取会话域对象的数据
            Object username = request.getSession().getAttribute("username");
            // 判断用户名
            if (username == null || "".equals(username)) {
                // 重定向到登录页面
                response.sendRedirect("/login.jsp");
                return;
            }
            // 放行
            filterChain.doFilter(request, response);
       // } catch (Exception e) {
            //e.printStackTrace();
        //}

        /*try{
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            HttpServletRequest request= (HttpServletRequest) servletRequest;
            Object username = request.getSession().getAttribute("username");
            if(username==null||"".equals("username")){
                response.sendRedirect("/login.jsp");
                return;
            }
            filterChain.doFilter(request,response);
        }catch(Exception e){
            e.printStackTrace();
        }*/
    }
}
